//
//  AppDelegate.m
//  FleaFinder
//
//  Created by Hieu Le on 4/6/13.
//  Copyright (c) 2013 Kiwiweb. All rights reserved.
//

#import "AppDelegate.h"
//#import "MarketType.h"
//#import "Category.h"
#import "Marked.h"

#import "XmlParserMarkedTypeList.h"
#import "XmlParserCategoryList.h"
#import "XmlParserMarkedListInCategory.h"

#import "GoogleMapXmlDataParser.h"

#import "Common.h"

@implementation AppDelegate

@synthesize common;

@synthesize marketTypeList, categoryList, marketList, businessMarketList, isLoadingMarketList, currentSelectedCategory, currentSelectedMarketType, dataOrganized, isLoadingLocation, storyBoard, markedInfoViewController, marketSummaryListViewController, mapViewController, markedTypeViewController, isLoadingBusinessMarketList, marketListWithLoadedLocation, isLoadingMoreMarketList, lastTimeLoadData, isLoadingMoreBusinessMarketList, isHasSomeMarketsLoaded;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    common = [[Common alloc] init];
    
    isLoadingMarketList = YES;
    isHasSomeMarketsLoaded = NO;
    isLoadingBusinessMarketList = YES;
    isLoadingLocation = YES;
    //marketListPageSize = 20;
    
    marketListWithLoadedLocation = [NSMutableArray arrayWithCapacity:50];
    
    //start a thread to load markettype list and category list from website.
    queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        
        marketList = [[NSMutableArray alloc] initWithCapacity:500];
        
        [self readMarketTypeListFromWebsite];
        [self readCategoryListFromWebsite];
        
        int sizeOfMarketList = -1;
        int nextPage = 0;
        while(sizeOfMarketList != [marketList count]){
            
            sizeOfMarketList = [marketList count];
            ++nextPage;
            
            [self readMarketListFromWebsiteWithPageSize:common.defaultPageSize andPageNum:nextPage];
            lastTimeLoadData = [NSDate dateWithTimeIntervalSinceNow:0];
            [self reformatDateOfMarket:marketList];
        }
        isLoadingMarketList = NO;
    });

    //start a thread to load all Top Markeders from website.
    queueTopMarkeder = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queueTopMarkeder, ^{
        
        businessMarketList = [[NSMutableArray alloc] initWithCapacity:50];

        int sizeOfMarketList = -1;
        int nextPage = 0;
        while(sizeOfMarketList != [businessMarketList count]){
            
            sizeOfMarketList = [businessMarketList count];
            ++nextPage;
            
            [self readTopMarketListFromWebsiteWithPageSize:common.defaultPageSize andPageNum:nextPage];
            [self reformatDateOfMarket:businessMarketList];
        }
    });
    //dispatch_release(queueTopMarkeder);
    
    queueGetLocation = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queueGetLocation, ^{
        [self getMarketLocations];
    });
    //dispatch_release(queueGetLocation);
    
    // Override point for customization after application launch.
    
    NSMutableDictionary *titleBarAttributes = [NSMutableDictionary dictionaryWithDictionary: [[UINavigationBar appearance] titleTextAttributes]];
    [titleBarAttributes setValue:[UIFont fontWithName:@"Georgia" size:18] forKey:UITextAttributeFont];
    [[UINavigationBar appearance] setTitleTextAttributes:titleBarAttributes];
    
    UIImage* backButtonImage = [UIImage imageNamed:@"back_btn"];
    [[UIBarButtonItem appearance] setBackButtonBackgroundImage:backButtonImage forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    
    [[UINavigationBar appearance] setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
    [[UINavigationBar appearance] setBackgroundColor:[UIColor blackColor]];
    
    return YES;
}
							
- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    //[self closeDatabaseConnection];
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    //[self closeDatabaseConnection];
}

/*-(void) checkAndCreateDatabase
{
    BOOL success;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    success = [fileManager fileExistsAtPath:databasePath];
    
    if(success) return;
    
    NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
    
    [fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
}

-(void) closeDatabaseConnection
{
    if(database){
        sqlite3_close(database);
        database = NULL;
    }
}

-(BOOL) connectToDatabase
{
    if(!database)
    {
        return (sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK);
    }
    return NO;
}

-(void) updateMarketTypeData: (NSMutableArray*) marketTypeListInput
{
    [self connectToDatabase];
    const char *sql = "INSERT INTO markettype VALUES(@mtid, @mtname, @pos)";
    sqlite3_stmt *compiledStatement;
    sqlite3_prepare_v2(database, sql, -1, &compiledStatement, NULL);
    
    sqlite3_exec(database, "BEGIN TRANSACTION", NULL, NULL, NULL);
    MarketType *temp = nil;
    
    for(int i = 0; i < [marketTypeListInput count]; ++i)
    {
        temp = (MarketType*)[marketTypeListInput objectAtIndex:i];
        sqlite3_bind_int(compiledStatement, 1, temp.markedId);
        sqlite3_bind_text(compiledStatement, 2, [temp.name UTF8String], -1, SQLITE_TRANSIENT);
        sqlite3_bind_int(compiledStatement, 3, temp.pos);

        
        sqlite3_step(compiledStatement);
        
        sqlite3_clear_bindings(compiledStatement);
        sqlite3_reset(compiledStatement);
    }
    
    sqlite3_exec(database, "END TRANSACTION", NULL, NULL, NULL);
    sqlite3_finalize(compiledStatement);
}

-(void) readMarketTypeListFromDB
{
    [self connectToDatabase];
    
    const char *sqlStatement = "SELECT * FROM markettype ORDER BY pos ASC";
    sqlite3_stmt *compiledStatement;
    
    if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK)
    {
        while(sqlite3_step(compiledStatement) == SQLITE_ROW)
        {
            int marketTypeId = sqlite3_column_int(compiledStatement, 0);
            NSString *marketTypeName = [NSString stringWithUTF8String:(char*)sqlite3_column_text(compiledStatement, 1)];
            
            MarketType *mt = [[MarketType alloc] init];
            mt.markedId = marketTypeId;
            mt.name = marketTypeName;
            
            [marketTypeList addObject:mt];
        }
    }
    sqlite3_finalize(compiledStatement);
}

-(void) cleanMarketTypeData
{
    [self connectToDatabase];
    
    const char *sqlStatement = "DELETE FROM markettype WHERE 1 = 1";
    sqlite3_stmt *compiledStatement;
    
    if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK)
    {
        sqlite3_step(compiledStatement);
    }
    sqlite3_finalize(compiledStatement);
}

-(void) updateCategoryData: (NSMutableArray*) categoryListInput
{
    [self connectToDatabase];
    const char *sql = "INSERT INTO category VALUES(@cid, @cname, @pos)";
    sqlite3_stmt *compiledStatement;
    sqlite3_prepare_v2(database, sql, -1, &compiledStatement, NULL);
    
    sqlite3_exec(database, "BEGIN TRANSACTION", NULL, NULL, NULL);
    Category *temp = nil;
    
    for(int i = 0; i < [categoryListInput count]; ++i)
    {
        temp = (Category*)[categoryListInput objectAtIndex:i];
        sqlite3_bind_int(compiledStatement, 1, temp.categoryId);
        sqlite3_bind_text(compiledStatement, 2, [temp.title UTF8String], -1, SQLITE_TRANSIENT);
        sqlite3_bind_int(compiledStatement, 3, temp.pos);
        
        sqlite3_step(compiledStatement);
        
        sqlite3_clear_bindings(compiledStatement);
        sqlite3_reset(compiledStatement);
    }
    
    sqlite3_exec(database, "END TRANSACTION", NULL, NULL, NULL);
    sqlite3_finalize(compiledStatement);
}

-(void) cleanCategoryData
{
    
}

-(void) updateMarketData: (NSMutableArray*) marketListInput
{
    [self connectToDatabase];
    const char *sql = "INSERT INTO market VALUES(@mid, @mname, @mroad, @mzip, @mcity, @sdatestart, @sdateend, @mdatestart, @mdateend, @mtimestart, @mtimeend, @mlong, @mlat)";
    sqlite3_stmt *compiledStatement;
    sqlite3_prepare_v2(database, sql, -1, &compiledStatement, NULL);
    
    sqlite3_exec(database, "BEGIN TRANSACTION", NULL, NULL, NULL);
    Marked *temp = nil;
    
    for(int i = 0; i < [marketListInput count]; ++i)
    {
        temp = (Marked*)[marketListInput objectAtIndex:i];
        sqlite3_bind_int(compiledStatement, 1, temp.marketId);
        sqlite3_bind_text(compiledStatement, 2, [temp.markedname UTF8String], -1, SQLITE_TRANSIENT);
        sqlite3_bind_text(compiledStatement, 3, [temp.road UTF8String], -1, SQLITE_TRANSIENT);
        sqlite3_bind_text(compiledStatement, 4, [temp.zip UTF8String], -1, SQLITE_TRANSIENT);
        sqlite3_bind_text(compiledStatement, 5, [temp.city UTF8String], -1, SQLITE_TRANSIENT);
        sqlite3_bind_text(compiledStatement, 6, [temp.datefrom UTF8String], -1, SQLITE_TRANSIENT);
        sqlite3_bind_text(compiledStatement, 7, [temp.dateto UTF8String], -1, SQLITE_TRANSIENT);
        sqlite3_bind_int(compiledStatement, 8, temp.datefrom_num);
        sqlite3_bind_int(compiledStatement, 9, temp.dateto_num);
        sqlite3_bind_text(compiledStatement, 10, [temp.startat UTF8String], -1, SQLITE_TRANSIENT);
        sqlite3_bind_text(compiledStatement, 11, [temp.endat UTF8String], -1, SQLITE_TRANSIENT);
        sqlite3_bind_double(compiledStatement, 12, temp.longtitude);
        sqlite3_bind_double(compiledStatement, 13, temp.lattitude);
        
        sqlite3_step(compiledStatement);
        
        sqlite3_clear_bindings(compiledStatement);
        sqlite3_reset(compiledStatement);
    }
    
    sqlite3_exec(database, "END TRANSACTION", NULL, NULL, NULL);
    sqlite3_finalize(compiledStatement);

}



-(void) readCategoryListFromDB
{
    [self connectToDatabase];
}

-(void) readMarketListFromDB
{
    
}
*/

-(void) readMarketTypeListFromWebsite
{
    if([self.marketTypeList count] > 0){
        return;
    }
//     NSString *linkToMarkedTypeList;
    
    XmlParserMarkedTypeList *xmlParser = [[XmlParserMarkedTypeList alloc] init];
    [xmlParser parseXML: common.linkToMarkedTypeList];
    
    self.marketTypeList = [xmlParser getParsedObjects];
    
    //init dataOrganized
    dataOrganized = [NSMutableDictionary dictionaryWithCapacity:[marketTypeList count]];
    for(int i = 0; i < [marketTypeList count]; ++i){
        [dataOrganized setObject:[NSMutableArray arrayWithCapacity:100] forKey:((MarketType*)[marketTypeList objectAtIndex:i]).name];
    }
}

-(void) readCategoryListFromWebsite
{
//     NSString *linkToCategoryList;
    
    XmlParserCategoryList *xmlParser = [[XmlParserCategoryList alloc] init];
    [xmlParser parseXML: common.linkToCategoryList];
    self.categoryList = [xmlParser getParsedObjects];
}

-(void) readMarketListFromWebsiteWithPageSize: (int) pageSize andPageNum:(int)pagenum
{
    // NSString *linkViewAll;
    
    NSString *fromUrl = [NSString stringWithFormat:common.linkViewAll, pageSize, pagenum];
    
    XmlParserMarkedListInCategory *xmlParser = [[XmlParserMarkedListInCategory alloc] init];
    //[xmlParser parseXML: fromUrl putIntoArray:marketList andOrganizedData:dataOrganized];
    [xmlParser parseXML:fromUrl putIntoArray:marketList andOrganizedData:dataOrganized inSortedManner:NO];
    isHasSomeMarketsLoaded = YES;
}

-(void) readTopMarketListFromWebsiteWithPageSize: (int) pageSize andPageNum:(int)pagenum
{
//     NSString *linkTopMarkeder;
    
    NSString *fromUrl = [NSString stringWithFormat:common.linkTopMarkeder, pageSize, pagenum];
    
    XmlParserMarkedListInCategory *xmlParser = [[XmlParserMarkedListInCategory alloc] init];
    //[xmlParser parseXML: fromUrl putIntoArray:businessMarketList andOrganizedData:nil]; 
    [xmlParser parseXML: fromUrl putIntoArray:businessMarketList andOrganizedData: nil inSortedManner:NO];
    //isLoadingMarketList = NO;
    isLoadingBusinessMarketList = NO;
}

-(void) readMoreMarketsFromWebsite: (NSString*) withUrl
{
    //------------------------ load MORE market list from website -------------------------
    isLoadingMoreMarketList = YES;
    
    NSMutableArray* tempArray = [NSMutableArray arrayWithCapacity:20];
    
    XmlParserMarkedListInCategory *xmlParser = [[XmlParserMarkedListInCategory alloc] init];
//    [xmlParser parseXML: withUrl putIntoArray:tempArray andOrganizedData: dataOrganized];
    [xmlParser parseXML: withUrl putIntoArray:tempArray andOrganizedData: dataOrganized inSortedManner: YES];
    lastTimeLoadData = [NSDate dateWithTimeIntervalSinceNow:0];
    
    [self formatDateOfMarkets:tempArray];
    /*Marked *m1 = nil, *m2 = nil, *m3 = nil;
    BOOL added = NO;
    
    for(int i = 0; i < [tempArray count]; ++i){
        
        m1 = (Marked*)[tempArray objectAtIndex:i];
        added = NO;
        
        for(int j = [marketList count] - 1; j >= 0; --j){
            m2 = (Marked*)[marketList objectAtIndex:j];
            
            if(m1.datefrom_num > m2.datefrom_num){
                [marketList insertObject:m1 atIndex:j + 1];
            } else if(m1.datefrom_num == m2.datefrom_num){
                for(int k = j; k >= 0; --k){
                    m3 = (Marked*)[marketList objectAtIndex:k];
                    if(m1.datefrom_num == m3.datefrom_num){
                        if(m1.dateto_num >= m3.dateto_num){
                            [marketList insertObject:m1 atIndex:k + 1];
                            added = YES;
                            break;
                        }
                    }
                }
                
                if(added){
                    break;
                }
            }
        }
    }*/
    [self addMarketsToMarketListInSortedManner:tempArray toList:marketList];
    isLoadingMoreMarketList = NO;
    
    [self getMarketLocationForMarketList:tempArray andLoadingFlag:&isLoadingMoreMarketList];
    [tempArray removeAllObjects];
    //------------------------ END OF load MORE market list from website -------------------------
 
    //------------------------ load MORE top market list from website -------------------------
//    xmlParser = [[XmlParserMarkedListInCategory alloc] init];
    //[xmlParser parseXML: common.linkLoadNewBusinessMarkets putIntoArray:tempArray andOrganizedData: nil];
    //[self addMarketsToMarketListInSortedManner:tempArray toList:businessMarketList];
    //[tempArray removeAllObjects];
    //------------------------ END OF load MORE top market list from website -------------------------
}

-(void) readMoreBusinessMarketsFromWebsite: (NSString*) withUrl
{
    //------------------------ load MORE market list from website -------------------------
    //isLoadingMoreMarketList = YES;
    
    NSMutableArray* tempArray = [NSMutableArray arrayWithCapacity:20];
    
    XmlParserMarkedListInCategory *xmlParser = [[XmlParserMarkedListInCategory alloc] init];
    //[xmlParser parseXML: withUrl putIntoArray:tempArray andOrganizedData: nil];
    [xmlParser parseXML: withUrl putIntoArray: tempArray andOrganizedData: nil inSortedManner: NO];
    
    //lastTimeLoadData = [NSDate dateWithTimeIntervalSinceNow:0];
    
    [self formatDateOfMarkets:tempArray];
    
    [self addMarketsToMarketListInSortedManner:tempArray toList:businessMarketList];
    //isLoadingMoreMarketList = NO;
    
    [self getMarketLocationForMarketList:tempArray andLoadingFlag:&isLoadingMoreBusinessMarketList];
    [tempArray removeAllObjects];
    //------------------------ END OF load MORE market list from website -------------------------
    
    //------------------------ load MORE top market list from website -------------------------
    //    xmlParser = [[XmlParserMarkedListInCategory alloc] init];
    //[xmlParser parseXML: common.linkLoadNewBusinessMarkets putIntoArray:tempArray andOrganizedData: nil];
    //[self addMarketsToMarketListInSortedManner:tempArray toList:businessMarketList];
    //[tempArray removeAllObjects];
    //------------------------ END OF load MORE top market list from website -------------------------
}

-(void) reformatDateOfMarket:(NSMutableArray*) marketListInput
{
    today =[NSDate dateWithTimeIntervalSinceNow:0];
    calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    
    if(!dateFormatter){
        dateFormatter = [[NSDateFormatter alloc]init];
        [dateFormatter setDateFormat:@"dd.MM.yy"];
    }
    
    Marked* m = nil;
    //NSDate* dateFrom = nil;
    //NSDate* dateTo = nil;
    //NSDate *today =[NSDate dateWithTimeIntervalSinceNow:0];
    
    //NSDateComponents *cdatefrom = nil;
    //NSDateComponents *cdateto = nil;
    //NSDateComponents *cdatetoday = nil;
    
    //NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    
    for(int i = 0; i < [marketListInput count]; ++i)
    {
        m = (Marked*)[marketListInput objectAtIndex:i];
        [self formatDateOfMarket:m];
    }
}

/*-(void) sortMarketList:(NSMutableArray*) marketListInput isTopList:(BOOL)topList
{
    NSSortDescriptor *sortDescriptor;
    sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"datefrom_num" ascending:YES];
    NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
    
    if(!topList){
        marketList = [marketListInput sortedArrayUsingDescriptors:sortDescriptors];
    } else {
        businessMarketList = [marketListInput sortedArrayUsingDescriptors:sortDescriptors];
    }
}*/

-(void) getMarketLocations
{
    // NSString *countryName;
    // NSString *googleMapApi;

    int stoppedAt = 0;
    GoogleMapXmlDataParser *googleMapXmlParser = [[GoogleMapXmlDataParser alloc] init];
    NSString *addr = nil, *url = nil;
    Marked* m = nil;
    
    BOOL allLoaded = NO;
    
    while(isLoadingMarketList || !allLoaded){
        
        allLoaded = !isLoadingMarketList;
        for(int i = stoppedAt; i < [marketList count]; ++i){
            m = (Marked*)[marketList objectAtIndex:i];
            if(m.isShownOnMap == YES){
                addr = [NSString stringWithFormat:@"%@, %@, %@", m.road, m.city, common.countryName];
                url = [NSString stringWithFormat:common.googleMapApi, [addr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
                
                [googleMapXmlParser parseXML:url];
                m.longtitude = googleMapXmlParser.lng;
                m.lattitude = googleMapXmlParser.lat;
                m.isLoadedLocation = YES;
                
                [marketListWithLoadedLocation addObject:m];
                
                //NSLog(@"loaded location for: %@", m.markedname);
            }
            stoppedAt = i + 1;
        }
        sleep(1);
    }
    isLoadingLocation = NO;
}

-(void) getMarketLocationForMarketList: (NSMutableArray*) inputMarketList andLoadingFlag:(BOOL*) isLoadingData
{
    int stoppedAt = 0;
    GoogleMapXmlDataParser *googleMapXmlParser = [[GoogleMapXmlDataParser alloc] init];
    NSString *addr = nil, *url = nil;
    Marked* m = nil;
    
    BOOL allLoaded = NO;
    
    while(*isLoadingData || !allLoaded){
        
        allLoaded = !*isLoadingData;
        for(int i = stoppedAt; i < [inputMarketList count]; ++i){
            m = (Marked*)[inputMarketList objectAtIndex:i];
            if(m.isShownOnMap == YES){
                addr = [NSString stringWithFormat:@"%@, %@, %@", m.road, m.city, common.countryName];
                url = [NSString stringWithFormat:common.googleMapApi, [addr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
                
                [googleMapXmlParser parseXML:url];
                m.longtitude = googleMapXmlParser.lng;
                m.lattitude = googleMapXmlParser.lat;
                m.isLoadedLocation = YES;
                
                [marketListWithLoadedLocation addObject:m];
                
                //NSLog(@"loaded location for: %@", m.markedname);
            }
            stoppedAt = i + 1;
        }
        sleep(1);
    }
    *isLoadingData = NO;
}

-(void) addMarketsToMarketListInSortedManner: (NSMutableArray*)marketsToAdd toList:(NSMutableArray*)destArray {
    Marked *m1 = nil, *m2 = nil, *m3 = nil;
    //BOOL added = NO;
    
    for(int i = 0; i < [marketsToAdd count]; ++i){
        
        m1 = (Marked*)[marketsToAdd objectAtIndex:i];
        
        //added = NO;
        /*for(int j = 0; j < [destArray count]; ++j){
            m2 = (Marked*)[destArray objectAtIndex:j];
            if(m2.marketId == m1.marketId){
                added = YES;
            }
        }
        if(added){
            continue;
        }
        
        for(int j = [destArray count] - 1; j >= 0; --j){
            m2 = (Marked*)[destArray objectAtIndex:j];
            
            if(m1.datefrom_num > m2.datefrom_num){
                [destArray insertObject:m1 atIndex:j + 1];
            } else if(m1.datefrom_num == m2.datefrom_num){
                for(int k = j; k >= 0; --k){
                    m3 = (Marked*)[destArray objectAtIndex:k];
                    if(m1.datefrom_num == m3.datefrom_num){
                        if(m1.dateto_num >= m3.dateto_num){
                            [destArray insertObject:m1 atIndex:k + 1];
                            added = YES;
                            break;
                        }
                    }
                }
                
                if(added){
                    break;
                }
            }
        }*/
        [self addMarketToMarketListInSortedManner:m1 toList:destArray];
    }
}

-(void) addMarketToMarketListInSortedManner: (Marked*)market toList:(NSMutableArray*)destArray {
    BOOL added = NO;
    Marked *m2 = nil, *m3 = nil;
    
    for(int j = 0; j < [destArray count]; ++j){
        m2 = (Marked*)[destArray objectAtIndex:j];
        if(m2.marketId == market.marketId){
            added = YES;
            [destArray insertObject:market atIndex:j + 1];
            [destArray removeObjectAtIndex:j];
            break;
        }
    }
    if(added){
        return;
    }
    
    for(int j = [destArray count] - 1; j >= 0; --j){
        m2 = (Marked*)[destArray objectAtIndex:j];
        
        if(market.datefrom_num > m2.datefrom_num){
            [destArray insertObject:market atIndex:j + 1];
        } else if(market.datefrom_num == m2.datefrom_num){
            for(int k = j; k >= 0; --k){
                m3 = (Marked*)[destArray objectAtIndex:k];
                if(market.datefrom_num == m3.datefrom_num){
                    if(market.dateto_num >= m3.dateto_num){
                        [destArray insertObject:market atIndex:k + 1];
                        added = YES;
                        break;
                    }
                }
            }
            
            if(added){
                break;
            }
        }
    }
    
    if(!added){
        [destArray insertObject:market atIndex:0];
    }
}

-(void)formatDateOfMarkets:(NSMutableArray*) markets {
    for(int i = 0; i < [markets count]; ++i){
        [self formatDateOfMarket:(Marked*)[markets objectAtIndex:i]];
    }
}

-(void) formatDateOfMarket:(Marked*) m
{
    NSDate* dateFrom = nil;
    NSDate* dateTo = nil;
    //NSDate *today =[NSDate dateWithTimeIntervalSinceNow:0];
    
    NSDateComponents *cdatefrom = nil;
    NSDateComponents *cdateto = nil;
    NSDateComponents *cdatetoday = nil;
    
    dateFrom = [NSDate dateWithTimeIntervalSince1970:m.datefrom_num];
    dateTo = [NSDate dateWithTimeIntervalSince1970:m.dateto_num];

    //NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    
    cdatefrom = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:dateFrom];
    cdateto = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:dateTo];
    cdatetoday = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:today];
    
    if(cdatefrom.year <= cdatetoday.year && cdatefrom.month <= cdatetoday.month && cdatefrom.day <= cdatetoday.day){
        m.isShownOnMap = YES;
    }
    
    if(cdatefrom.year == cdatetoday.year && cdatefrom.month == cdatetoday.month)
    {
        if(cdatefrom.day == cdatetoday.day)
        {
            m.datefrom = @"I dag";
        }
        else if(cdatefrom.day - cdatetoday.day == 1){
            m.datefrom = @"I morgen";
        }
    }
    
    if(cdateto.year == cdatetoday.year && cdateto.month == cdatetoday.month)
    {
        if(cdateto.day == cdatetoday.day)
        {
            m.dateto = @"I dag";
        }
        else if(cdateto.day - cdatetoday.day == 1){
            m.dateto = @"I morgen";
        }
    }
}

-(void) startReadMoreMarketListFromWebsite:(id)dataUser {
    
    if(!lastTimeLoadData){
        return;
    }
    
    [self removeOutOfDateMarkets:marketList];
    [self removeOutOfDateMarkets:businessMarketList];
    [self removeOutOfDateMarkets:marketListWithLoadedLocation];
    
    NSArray* keys = [dataOrganized allKeys];
    MarketType* type = nil;
    for(int i = 0; i < [keys count]; ++i){
        type = (MarketType*)[keys objectAtIndex:i];
        NSMutableArray* marketsArray = [dataOrganized objectForKey: type];
        [self removeOutOfDateMarkets:marketsArray];
    }
    
    NSDateComponents *dcLoadTime = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit fromDate:lastTimeLoadData];
    NSString *url = [NSString stringWithFormat:common.linkLoadNewMarkets, dcLoadTime.year, dcLoadTime.month, dcLoadTime.day, dcLoadTime.hour, dcLoadTime.minute, dcLoadTime.second];
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    NSString *urlBusiness = [NSString stringWithFormat:common.linkLoadNewBusinessMarkets, dcLoadTime.year, dcLoadTime.month, dcLoadTime.day, dcLoadTime.hour, dcLoadTime.minute, dcLoadTime.second];
    urlBusiness = [urlBusiness stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    queueReadMoreMarket = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queueReadMoreMarket, ^{
        [self readMoreMarketsFromWebsite:url];
        
        [self readMoreBusinessMarketsFromWebsite:urlBusiness];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [dataUser performSelector:@selector(startUpdateNewMarkets)];
        });
    });
}

/**
 * If you load data at 11:40PM, the he uses the app to 00:20AM of the next morning => the date is now should be increased by 1.
 * Then the app needs to check if some Markets have become unavailable (the current date passed its DateTo).
 */
-(void) removeOutOfDateMarkets:(NSMutableArray*) markets
{
    Marked* m = nil;
    NSDate* dateTo = nil;
    NSDateComponents *cdateto = nil;
    NSDateComponents *cdatetoday = nil;
    
    cdatetoday = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:today];
    
    for(int i = [markets count] - 1; i >= 0; --i){
        m = (Marked*)[markets objectAtIndex:i];
        
        dateTo = [NSDate dateWithTimeIntervalSince1970:m.dateto_num];
        cdateto = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:dateTo];
     
        if(cdateto.year < cdatetoday.year)
        {
            [markets removeObjectAtIndex:i];
        } else if(cdateto.year == cdatetoday.year){
            if(cdateto.month < cdatetoday.month){
                [markets removeObjectAtIndex:i];
            } else if(cdateto.month == cdatetoday.month){
                if(cdateto.day < cdatetoday.day){
                    [markets removeObjectAtIndex:i];
                }
            }
        }
    }
}

@end
